package server

import (
	"errors"
	"log"
	"weekly1/pkg"
	"weekly1/user-server/initiate/mysql"
	"weekly1/user-server/protot/user"
)

func UserRegister(in *user.UserRegisterReq) (*user.UserRegisterResp, error) {
	m := mysql.User{
		Name:     in.Name,
		Phone:    in.Phone,
		Password: pkg.Md5Password(in.Password),
	}
	err := m.Find(in.Phone)
	if err != nil {
		log.Println("未查到该账号")
		return nil, errors.New("未查到该账号")
	}
	err = m.Created()
	if err != nil {
		log.Println("用户注册失败")
		return nil, errors.New("用户注册失败")
	}
	return &user.UserRegisterResp{
		Code:  200,
		Greet: "用户注册成功",
	}, nil
}

func UserLogin(in *user.UserLoginReq) (*user.UserLoginResp, error) {
	m := mysql.User{}
	err := m.Find(in.Phone)
	if err != nil {
		log.Println("未查询到数据")
		return nil, errors.New("未查询到数据")
	}
	if m.ID == 0 {
		log.Println("未找到该账号请前往注册")
		return nil, errors.New("未找到该账号请前往注册")
	}
	if pkg.Md5Password(in.Password) != m.Password {
		log.Println("当前密码不正确")
		return nil, errors.New("当前密码不正确")
	}
	token, err := pkg.NewJWT("2210a").CreateToken(pkg.CustomClaims{
		ID: m.ID,
	})
	if err != nil {
		log.Println("当前用户未登录不允许播放")
		return nil, errors.New("当前用户未登录不允许播放")
	}
	return &user.UserLoginResp{
		Code:  200,
		Greet: token,
	}, nil
}

func VideoList(in *user.VideoListReq) (*user.VideoListResp, error) {
	v := mysql.Video{}
	l, err := v.List(in.Name)
	if err != nil {
		log.Println("未接收到参数")
		return nil, errors.New("未接收到参数")
	}
	var list []*user.VideoList
	for _, vi := range l {
		lists := &user.VideoList{
			Name:    vi.Name,
			Date:    vi.Date,
			Content: vi.Content,
			Status:  vi.Status,
		}
		list = append(list, lists)
	}
	return &user.VideoListResp{List: list}, nil
}

func VideoAdd(in *user.VideoAddReq) (*user.VideoAddResp, error) {
	v := mysql.Video{
		Name:    in.Name,
		Date:    in.Date,
		Content: in.Content,
		Status:  in.Status,
	}
	err := v.Create()
	if err != nil {
		log.Println("视频添加上传失败")
		return nil, errors.New("视频添加上传失败")
	}
	return &user.VideoAddResp{Greet: "视频上传成功"}, nil
}
